import Tkinter as tk


class GameBoard(tk.Frame):
    def __init__(self, rows=20, columns=20, size=16,
                  color1="white", color2="blue"):
        '''size is the size of a square, in pixels'''

        self.rows = rows
        self.columns = columns
        self.size = size
        self.color1 = color1
        self.color2 = color2
        self.pieces = {}
        self.parent = tk.Tk()
        canvas_width = columns * size
        canvas_height = rows * size + 10

        tk.Frame.__init__(self, self.parent)
        self.canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0,
                                width=canvas_width, height=canvas_height,
                                background="bisque")
        self.canvas.pack(side="top", fill="both", expand=True, padx=2, pady=2)

        self.text = text = tk.Text(self, height=10)
        text.pack()

        # this binding will cause a refresh if the user interactively
        # changes the window size
        self.canvas.bind("<Configure>", self.refresh)
        self.pack(side="top", fill="both", expand="true", padx=4, pady=4)

    def placepiece(self, row, col, color, player):
        '''Place a piece at the given row/column'''
        self.pieces[(row, col)] = color, player

    def write(self, string):
        self.text.insert(tk.INSERT, string)

    def draw(self):
        self.canvas.delete("square")
        for row in range(self.rows):
            for col in range(self.columns):
                x1 = (col * self.size)
                y1 = (row * self.size)
                fill, player = self.pieces.get((row, col), ('white', None))
                self.canvas.create_rectangle(x1, y1, x1 + self.size, y1 + self.size,
                                             outline="black",
                                             fill=fill, tags="square")
        self.canvas.tag_raise("piece")
        self.canvas.tag_lower("square")
        self.canvas.tag_lower("oval")

    def refresh(self, event):
        '''Redraw the board, possibly in response to window being resized'''
        xsize = (event.width - 1) // self.columns
        ysize = (event.height - 1) // self.rows
        self.size = min(xsize, ysize)
        self.draw()

    def mainloop(self):
        self.parent.mainloop()

if __name__ == "__main__":
    board = GameBoard()
    board.placepiece(0, 0, 'black')
    board.mainloop()
